using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Treeerarh
{
    public partial class Form1 : Form
    {
        trDocument doc;
        Options options;
        bool dirty;
        public Form1()
        {
            InitializeComponent();
            dirty = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            options = Options.Load();
            tree.CheckBoxes = options.ShowCheckBoxes;
            LoadLastDoc();
        }

        private void LoadLastDoc()
        {
            if (options.LoadLastFile && options.LastFileName != "")
                LoadFile(options.LastFileName);
            else
                NewFile();
        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            if (openFile.ShowDialog()==DialogResult.OK)
                        LoadFile(openFile.FileName);
        }

        private void LoadFile(string p)
        {
            doc = new trDocument();
            doc.loadFile(p);
            doc.getTreeNodes(tree.Nodes,true);
            es = EditingState.esNo;
            options.AddResentFile(p);
            MenuResentFiles();


        }

        private void MenuResentFiles()
        {
            mResentFiles.MenuItems.Clear();
            foreach (string file in options.ResentFiles)

                {
                    if (System.IO.File.Exists(file))
                    {
                        MenuItem rItem = new MenuItem();
                        rItem.Text = file;
                        rItem.Click += new System.EventHandler(LoadResentFile);
                        if (file == doc.originalFileName)
                        {
                            rItem.Enabled = false;
                            rItem.Checked = true;
                        }

                        mResentFiles.MenuItems.Add(rItem);
                    }
                }
            
        }

        private void LoadResentFile(object sender, EventArgs e)
        {
            LoadFile(((MenuItem)sender).Text);
        }


        private void Notify(String e)
        {
            Notify(e, 2);
        }

        private void Notify(String e, int delay)
        {
            notification.InitialDuration = delay;
            notification.Caption = "Details";
            notification.Text =   e;
            notification.Visible = true;
        }

        private void contextMenu1_Popup(object sender, EventArgs e)
        {
            AddSibling.Enabled = Delete.Enabled = Cut.Enabled = tree.SelectedNode.Parent != null;
            Paste.Enabled = unicodeInClipboard();
            ShowDescriptionItem.Enabled=((trDocNode)tree.SelectedNode).description!="";
            CancelEdit();
        }

        private void Rename_Click(object sender, EventArgs e)
        {
            EditNode(tree.SelectedNode);
            
        }

        public enum EditingState { esNo, esEditing, esLostFocus}
        private EditingState es;
        private void EditNode(TreeNode node)
        {
            Editor.Text = ((trDocNode)node).name;
            numberEdit.Text = ((trDocNode)node).number.ToString();

            Editor.Visible = true;
            EditorOK.Visible = true;
            numberEdit.Visible = true;
            
            editingNode = node;
            es = EditingState.esEditing;
            inputPanel1.Enabled = true;
            Editor.Focus();

        }

        private void Form1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("formClick");
        }

        private void CheckBoxes_Click(object sender, EventArgs e)
        {
            tree.CheckBoxes = !tree.CheckBoxes;
        }
        private TreeNode editingNode;

        private void EditorOK_Click(object sender, EventArgs e)
        {
            PostEdit();
        }

        private void PostEdit()
        {
            EditorOK.Visible = false;
            Editor.Visible = false;
            numberEdit.Visible = false;
            ((trDocNode)editingNode).name = Editor.Text;
            try
            {
                ((trDocNode)editingNode).number = System.Convert.ToDouble(numberEdit.Text);
            }
            catch (Exception) { ((trDocNode)editingNode).number = 0; }
            es = EditingState.esNo;
            inputPanel1.Enabled =false;
            tree.Focus();
            //tree.Invalidate();
            if (options.AutoSaveFile)
                SaveFile();
            else
                dirty = true;

        }

        private void Editor_LostFocus(object sender, EventArgs e)
        {
            es = EditingState.esLostFocus;
        }

        private void tree_GotFocus(object sender, EventArgs e)
        {
            CancelEdit();
        }

        private void CancelEdit()
        {
            if (es == EditingState.esLostFocus)
            {
                Editor.Visible = false;
                numberEdit.Visible = false;
                EditorOK.Visible = false;
                inputPanel1.Enabled = false;
                es = EditingState.esNo;
                tree.Focus();
            }

        }

        private void tabControl1_GotFocus(object sender, EventArgs e)
        {
            CancelEdit();
        }

        private void Editor_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                numberEdit.Focus();
                numberEdit.SelectAll();
                e.Handled = true;
            }
        }

        private void menuItem3_Click(object sender, EventArgs e)
        {
            CancelEdit();
            SaveFile();
        }

        private void SaveFile()
        {
            if (doc != null)
            {
                if (String.IsNullOrEmpty(doc.originalFileName))
                {
                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        doc.originalFileName = saveFileDialog.FileName;
                    }
                }
                options.AddResentFile(doc.originalFileName);
                doc.saveFile("", tree.Nodes[0]);
                MenuResentFiles();
            }
        }

        private void menuItem9_Click(object sender, EventArgs e)
        {
            EditNode(tree.SelectedNode);
        }

        private void menuItem8_Click(object sender, EventArgs e)
        {

            if (doc != null)
            {
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    doc.saveFile(saveFileDialog.FileName, tree.Nodes[0]);
                    options.LastFileName = doc.originalFileName;
                }

            }
        }

        private void menuItem7_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void Form1_Closing(object sender, CancelEventArgs e)
        {
            e.Cancel = false;
            try
            {
                options.LastFileName = doc.originalFileName;
                options.Save();
            }
            catch (Exception ex) { MessageBox.Show("Saving options: "+ex.Message); }
            if (doc != null)
            {
                try
                {
                    if (options.saveOnExit)
                        SaveFile();
                }
                catch (Exception )
                {
                    
                }

            }

        }

        private void AddChild_Click(object sender, EventArgs e)
        {
            doAddChild();
        }

        private void doAddChild()
        {
            trDocNode newnode = new trDocNode("");
                tree.SelectedNode.Nodes.Add(newnode);
            EditNode(newnode);
            tree.SelectedNode = newnode;

        }

        private void AddSibling_Click(object sender, EventArgs e)
        {
            doAddSibling();
        }

        private void doAddSibling()
        {
            trDocNode newnode = new trDocNode("");
            tree.SelectedNode.Parent.Nodes.Add(newnode);
            EditNode(newnode);
            tree.SelectedNode = newnode;
        }

        private void Delete_Click(object sender, EventArgs e)
        {
            tree.SelectedNode.Parent.Nodes.Remove(tree.SelectedNode);
        }

        private void menuItem10_Click(object sender, EventArgs e)
        {
            doAddSibling();
        }

        private void menuItem11_Click(object sender, EventArgs e)
        {
            doAddChild();

        }

        private void tabPage3_GotFocus(object sender, EventArgs e)
        {
            optionsToScreen();
        }

        private void optionsToScreen()
        {
            showcheckboxes.Checked = options.ShowCheckBoxes;
            autosavefile.Checked = options.AutoSaveFile;
            saveonexit.Checked = options.saveOnExit;
            loadlastfile.Checked = options.LoadLastFile;
            lastfilename.Text = options.LastFileName;
        }

        private void tabPage3_LostFocus(object sender, EventArgs e)
        {
            options.Save();
        }

        private void showcheckboxes_Click(object sender, EventArgs e)
        {
            tree.CheckBoxes = options.ShowCheckBoxes = showcheckboxes.Checked;
            if (tree.CheckBoxes)
                doc.updateCheckBoxes(tree.Nodes[0]);
            
        }

        private void autosavefile_CheckStateChanged(object sender, EventArgs e)
        {
            options.AutoSaveFile = autosavefile.Checked;
        }

        private void saveonexit_CheckStateChanged(object sender, EventArgs e)
        {
            options.saveOnExit = saveonexit.Checked;
        }

        private void loadlastfile_CheckStateChanged(object sender, EventArgs e)
        {
            options.LoadLastFile = loadlastfile.Checked;
        }

        private void lastfilename_TextChanged(object sender, EventArgs e)
        {
            options.LastFileName = lastfilename.Text; 
        }

        Boolean detailsEditing;
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (detailsEditing)
            {
                screeToNode();
                detailsEditing = false;
            }
            if (tabControl1.SelectedIndex == 2)
                optionsToScreen();
            if (tabControl1.SelectedIndex == 1)
            {
                detailsEditing = true;
                nodeToScreen();
            }
        }

        private void nodeToScreen()
        {
            try
            {
                trDocNode node = (trDocNode)tree.SelectedNode;

                EditNodeName.Text = node.name;
                numberBox.Text = node.number.ToString();
                descrBox.Text = node.description;
            }
            catch (Exception) { }
        }

        private void menuItem4_Click(object sender, EventArgs e)
        {
            NewFile();
        }

        private void NewFile()
        {
            if (doc == null)
                doc = new trDocument();
            if (dirty)
            {               
                SaveFile();
                dirty = false;
            }

            doc.newFile();
            doc.getTreeNodes(tree.Nodes, true);
            es = EditingState.esNo;
        }

        private void tree_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (trDocument.LoadingNow) return;
            if (tree.CheckBoxes)
            {
                ((trDocNode)e.Node).completed = e.Node.Checked;
                doc.checksUp(e.Node);
            }
            if (options.AutoSaveFile)
            {
                SaveFile();
            }
            else
                dirty = true;

            
        }

        private void tree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            mAdd.Enabled = tree.SelectedNode.Parent != null;
        }

        private void tabPage2_LostFocus(object sender, EventArgs e)
        {
            screeToNode();
        }

        private void screeToNode()
        {
            trDocNode node = (trDocNode)tree.SelectedNode;
            node.description = descrBox.Text;
            try
            {
                node.number = System.Convert.ToDouble(numberBox.Text);
            }
            catch (Exception) { }

            node.markDescription();
            if (options.AutoSaveFile)
            {
                SaveFile();
            }

            tree.Invalidate();
            tree.Focus();
//            tree.Refresh();
        }

        private void Cut_Click(object sender, EventArgs e)
        {
            doCut();
        }

        private void doCut()
        {
            doCopy();
            tree.SelectedNode.Parent.Nodes.Remove(tree.SelectedNode);
        }

        private void doCopy()
        {
            DataObject DO = new DataObject();
            DO.SetData(DataFormats.UnicodeText, ((trDocNode)tree.SelectedNode).toXMLString());
            Clipboard.SetDataObject(DO);
        }

        private void Paste_Click(object sender, EventArgs e)
        {
            doPaste();
        }

        private void doPaste()
        {
            try
            {

                if (!unicodeInClipboard()) { return; }

                trDocNode node = new trDocNode("");
                node.fromXMLString((string)((IDataObject)Clipboard.GetDataObject()).GetData(DataFormats.UnicodeText));
                if (tree.SelectedNode.Nodes.Count > 0) // has children
                {
                    tree.SelectedNode.Nodes.Add(node);
                }
                else
                {
                    if (tree.SelectedNode.Parent != null)
                    {
                        tree.SelectedNode.Parent.Nodes.Insert(tree.SelectedNode.Index, node);
                    }
                }
            }
            catch (Exception ex) { }

        }

        private static bool unicodeInClipboard()
        {
            return ((IDataObject)Clipboard.GetDataObject()).GetDataPresent(DataFormats.UnicodeText);
        }

        private void menuItem10_Click_1(object sender, EventArgs e)
        {
            doCopy();
        }

        private void menuItem11_Click_1(object sender, EventArgs e)
        {
            Notify(((trDocNode) tree.SelectedNode).description);
        }

        private void numberEdit_GotFocus(object sender, EventArgs e)
        {
            es = EditingState.esEditing;
        }

        private void numberEdit_LostFocus(object sender, EventArgs e)
        {
            es = EditingState.esLostFocus;
        }

        private void numberEdit_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                PostEdit();
                e.Handled = true;
            }

        }

        private void menuItem11_Click_2(object sender, EventArgs e)
        {
            trDocNode topNode = ((trDocNode)tree.SelectedNode);
            topNode.number=SumUp(topNode);
            
        }

        private double SumUp(trDocNode topNode)
        {
            double ret=0;
            foreach (TreeNode node in topNode.Nodes)
            {
                if (node.Nodes.Count > 0)
                    ((trDocNode)node).number= SumUp((trDocNode)node);
                ret += ((trDocNode)node).number;
            }
            return ret;
        }

 
     }
}